import arch
import regs
import instructions

org = 0
labels = {}

def explain(cmd, line):
    tokens = [cmd]
    match cmd:
        case 'org':  # 标记加载位置
            org = line[0][1]
            tokens = None
        case _:
            for item in line:
                tokens.append(item[1])
    return tokens

def detoken(tokenlist):
    global labels
    tokens = []
    for line in tokenlist:  # 遍历行
        line_id = line[0]  # 行号
        items = line[1:]  # 去掉行号

        match items[0][0]:  # 获取第一项的类型
            case 'id':
                ret = explain(items[0][1], items[1:])
                if not ret == None:  # 伪指令跳过
                    tokens.append(ret)
            case 'label':  # 标签
                labels[items[0][1]] = len(tokens)*arch.COMMAND_SIZE
                if len(items)>1:
                    print("ERROR in line ", line_id, ", label has extra tokens.")
            case _ as x:
                print("ERROR in line ", line_id, ", invalid token type at first: ", x)
                exit(1)

    labels |= regs.regs
    for code in tokens:  # 替换label
        if not code[0] in instructions.fake_cmd:
            for i in range(1, len(code)):
                if code[i] in labels:
                    code[i] = org + labels[code[i]]

    return tokens
